<script setup>
// import语句
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getclass, transfer, delcoursestudent } from '@/api/myClass.js'
import { getcourse } from '@/api/courses.js'

// 响应式变量定义
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
})
const jumpPage = ref(1)

// 表格相关
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
// 课程列表
const courseList = ref([])
const selectedCourse = ref(null)

// 转班对话框相关
const transferDialogVisible = ref(false)
const currentRow = ref(null)

// 获取班级列表数据
const getClassList = async () => {
  loading.value = true
  try {
    const { code, data, msg } = await getclass(queryParams)
    if (code !== 200) {
      throw new Error(msg)
    }
    tableData.value = data.records
    total.value = data.total
  } catch (error) {
    ElMessage.error(error.message || '获取数据失败')
  } finally {
    loading.value = false
  }
}

// 获取课程列表
const getCourseList = async () => {
  const { code, data, msg } = await getcourse()
  if (code !== 200) {
    throw new Error(msg)
  }
  courseList.value = data.records
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getClassList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getClassList()
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  getClassList()
}

// 添加页面跳转功能
const handleJumpPage = () => {
  const pageNum = parseInt(jumpPage.value)
  if (
    isNaN(pageNum) ||
    pageNum < 1 ||
    pageNum > Math.ceil(total.value / queryParams.pageSize)
  ) {
    ElMessage.warning('请输入有效的页码')
    jumpPage.value = queryParams.pageNum
    return
  }
  queryParams.pageNum = pageNum
  getClassList()
}

// 处理转班操作
/**
 * 处理转班操作（使用 async/await）
 * @param {Object} row - 当前行数据
 */
const handleTransfer = (row) => {
  // 重置选中的课程
  selectedCourse.value = null
  // 保存当前行数据
  currentRow.value = row
  // 显示转班对话框
  transferDialogVisible.value = true
}

// 确认转班
const confirmTransfer = async () => {
  // 如果没有选择班级，则提示并返回
  if (!selectedCourse.value) {
    ElMessage.warning('请选择班级')
    return
  }

  const params = {
    id: currentRow.value.id,
    oldTcdId: currentRow.value.tcdId,
    newTcdId: parseInt(selectedCourse.value),
    userId: currentRow.value.userId,
    roundId: currentRow.value.roundId,
  }

  try {
    const res = await transfer(params)
    if (res.code === 200) {
      ElMessage.success('转班成功')
      // 关闭对话框
      transferDialogVisible.value = false
      // 重置选择的课程
      selectedCourse.value = null
      // 刷新列表
      getClassList()
    } else {
      throw new Error(res.msg)
    }
  } catch (error) {
    ElMessage.error(error.message || '转班失败')
  }
}

/**
 * 处理移除操作（使用 async/await）
 * @param {Object} row - 当前行数据
 */
const handleRemove = async (row) => {
  try {
    await ElMessageBox.confirm('确认要将该学生从班级中移除吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const params = {
      tcdId: row.tcdId,
      userId: row.id,
    }
    try {
      const res = await delcoursestudent(params)
      if (res.code === 200) {
        ElMessage.success('移除成功')
        getClassList()
      } else {
        throw new Error(res.msg)
      }
    } catch (error) {
      throw new Error(error.message)
    }
  } catch (error) {
    // 用户取消操作，无需处理
    throw new Error(error.message)
  }
}

onMounted(() => {
  getClassList()
  // 获取课程列表
  getCourseList()
})
</script>

<template>
  <div class="class-manage p-4" tabindex="0">
    <!-- 操作按钮区域 -->
    <div class="mb-4 flex flex-wrap gap-2 items-center">
      <el-input
        v-model="queryParams.name"
        placeholder="请输入班级名称"
        style="width: 200px"
        clearable
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" border>
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column prop="name" label="姓名" min-width="120" />
      <el-table-column prop="deptName" label="所属院系" min-width="150" />
      <el-table-column prop="phone" label="联系电话" min-width="120" />
      <!-- 操作 -->
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-button
            plain
            type="primary"
            size="small"
            @click="handleTransfer(scope.row)"
          >
            转班
          </el-button>
          <el-button
            plain
            type="danger"
            size="small"
            @click="handleRemove(scope.row)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="mt-4 flex items-center text-sm text-gray-500">
      <span>共 {{ total }} 条</span>
      <div class="ml-4 flex items-center">
        <el-select
          v-model="queryParams.pageSize"
          class="!w-[100px] mr-2"
          @change="handleSizeChange"
        >
          <el-option
            v-for="size in [10, 20, 30, 50]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          layout="prev, pager, next"
          :total="total"
          :pager-count="5"
          background
          @current-change="handleCurrentChange"
        />
        <span class="mx-2">前往</span>
        <el-input
          v-model="jumpPage"
          class="!w-[50px]"
          @keyup.enter="handleJumpPage"
        />
        <span class="mx-2">页</span>
      </div>
    </div>

    <!-- 转班对话框 -->
    <el-dialog
      v-model="transferDialogVisible"
      title="转班操作"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="transfer-dialog-content">
        <p class="mb-2">请选择要转入的课程:</p>
        <el-select
          v-model="selectedCourse"
          placeholder="请选择班级"
          style="width: 100%"
          filterable
          clearable
        >
          <el-option
            v-for="course in courseList"
            :key="course.id"
            :label="course.courseName"
            :value="course.id"
          />
        </el-select>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="transferDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmTransfer">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>
.class-manage {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .el-table {
    height: calc(100vh - 270px);
  }
}

.transfer-dialog-content {
  padding: 10px 0;
}
</style>
